package com.tinyproxy.common;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

import static com.tinyproxy.common.CodecKind.DECRYPT;
import static com.tinyproxy.common.CodecKind.ENCRYPT;

/**
 * @author Administrator
 */
public class ExchangeHandler extends ChannelInboundHandlerAdapter {

    private final Logger log = LoggerFactory.getLogger(getClass());

    private final byte[] xtoken;

    private final Channel relayChannel;

    private final CodecKind codec;

    private int iToken = 0;

    public ExchangeHandler(byte[] xtoken, Channel relayChannel, CodecKind codec) {
        this.xtoken = xtoken;
        this.relayChannel = relayChannel;
        this.codec = codec;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        relayChannel.writeAndFlush(Unpooled.EMPTY_BUFFER);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        if (relayChannel.isActive()) {
            ByteBuf buf = (ByteBuf) msg;
            if (codec == ENCRYPT) {
                iToken = Kits.encrypt(xtoken, buf, iToken, buf.readableBytes());
            } else if (codec == DECRYPT) {
                iToken = Kits.decrypt(xtoken, buf, iToken, buf.readableBytes());
            }

            relayChannel.writeAndFlush(msg);
        } else {
            ReferenceCountUtil.release(msg);
        }
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        Kits.closeOnFlush(ctx.channel());
        Kits.closeOnFlush(relayChannel);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        if (!(cause instanceof IOException)) {
            log.warn("--Exchange--" + cause);
        }
        Kits.closeOnFlush(ctx.channel());
        Kits.closeOnFlush(relayChannel);
    }

}
